package top.timous.controller.student;

import cn.hutool.core.util.RandomUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.timous.pojo.ScoreEntity;
import top.timous.pojo.StudentEntity;
import top.timous.service.StudentService;
import top.timous.util.MD5Util;
import top.timous.util.RandImageUtil;
import top.timous.util.RedisUtil;
import top.timous.vo.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/student")
public class StudentController {

    private static final String BASE_CHECK_CODES = "qwertyuiplkjhgfdsazxcvbnmQWERTYUPLKJHGFDSAZXCVBNM1234567890";

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private StudentService studentService;

    @ApiOperation("学生登录")
    @PostMapping("/login")
    public AjaxResult<StudentEntity> login(@RequestBody StudentLogin studentLogin , HttpSession session){
        System.out.println("============="+session.getId());
        String password = MD5Util.MD5Encode(studentLogin.getStuPassword(), "utf-8");
        String msg = "";
        AjaxResult<StudentEntity> res = new AjaxResult<>();
        StudentEntity studentEntity = new StudentEntity();
        studentEntity.setStuId(studentLogin.getStuId());
        String s = studentLogin.getCaptcha().toLowerCase();
        studentEntity.setStuPassword(password);
        StudentEntity student = studentService.queryStudentByIdAndPwd(studentEntity);
        if(redisUtil.get("captcha") == null){
            res.setCode(1);
            msg = "验证码已过期！！";
        }else {
            if (s.equals(redisUtil.get("captcha"))){
                if (student == null){
                    msg = "用户名或密码错误！！";
                    res.setCode(1);
                }else {
                    student.setStuPassword("");
                    res.setData(student);
                    session.setAttribute("student" , student);
                    msg = "登录成功！！";
                    res.setCode(0);
                }
            }else {
                res.setCode(1);
                msg = "验证码错误";
            }
        }
        System.out.println(student);
        res.setMsg(msg);
        return res;
    }
    @ApiOperation("退出登录")
    @PostMapping("/logout")
    public AjaxResult<String> logout(HttpSession session){
        AjaxResult<String> res = new AjaxResult<>();
        session.removeAttribute("student");
        res.setCount(0);
        res.setCode(0);
        res.setMsg("");
        res.setData("");
        return res;
    }

    @ApiOperation("获取验证码的值")
    @GetMapping("/getCode")
    public AjaxResult<String> getCode(){
        String realKey = (String) redisUtil.get("captcha");
        AjaxResult<String> res = new AjaxResult<String>();
        res.setData(realKey);
        res.setMsg("请求成功！");
        res.setCode(1);
        return res;
    }

    /**
     * 验证码
     * 别人做的，返回的结果集需要修改
     * @param key
     * @return
     */
    @ApiOperation("获取验证码")
    @GetMapping(value = "/randomImage")
    public AjaxResult<String> randomImage(String key , HttpSession session){
        AjaxResult<String> res = new AjaxResult<String>();
        try {
            String code = RandomUtil.randomString(BASE_CHECK_CODES,4);
            String lowerCaseCode = code.toLowerCase();
            String realKey = "captcha";
            //每次刷新验证码的时候  把验证码缓存一分钟
            redisUtil.set(realKey, lowerCaseCode, 120);
            String base64 = RandImageUtil.generate(code);
            res.setData(base64);
            System.out.println(lowerCaseCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }


    @ApiOperation("个人的基本的信息")
    @GetMapping("/userInfo")
    public AjaxResult<StudentEntity> userInfo(HttpSession session){
        AjaxResult<StudentEntity> res = new AjaxResult<>();
        StudentEntity student = (StudentEntity) session.getAttribute("student");
        StudentEntity studentEntity = studentService.queryStudentById(student);
        res.setMsg("查找信息成功");
        res.setCode(0);
        res.setData(studentEntity);
        res.setCount(0);
        return res;
    }
//    @ApiOperation("查询所有课程并且准备选课")
//    @GetMapping("/allCourse")
//    public AjaxResult<List<CourseTable>> allCourse(int page , int limit , HttpSession session){
//        AjaxResult<List<CourseTable>>  res = new AjaxResult<>();
//        // 增加分页
//        PageSize<String> pageSize = new PageSize<>();
//        pageSize.setPage((page - 1) * limit);
//        pageSize.setSize(limit);
//        List<CourseTable> list = studentService.queryAllCourse(pageSize);
//        res.setMsg("查找信息成功");
//        res.setCode(0);
//        res.setData(list);
//        res.setCount(studentService.queryAllCourseCount());
//        return res;
//    }
    @ApiOperation("查询所有课程并且准备选课,并且加上搜索")
    @GetMapping("/allCourse")
    public AjaxResult<List<CourseTable>> allCourse(CourseTable courseTable, HttpSession session){
        int page = (courseTable.getPage() - 1) * courseTable.getLimit();
        courseTable.setPage(page);
        System.out.println(courseTable);
        AjaxResult<List<CourseTable>>  res = new AjaxResult<>();
        List<CourseTable> list = studentService.queryAllCourseByCourseTable(courseTable);
        res.setCount(studentService.queryAllCourseByCourseTableCount(courseTable));
        res.setData(list);
        res.setCode(0);
        res.setMsg("查询成功");
        return res;
    }

    @ApiOperation("获取学生的详细信息")
    @GetMapping("getStudentInfo")
    public AjaxResult<StudentInfo> getStudentInfo(HttpSession session){
        AjaxResult<StudentInfo> res = new AjaxResult<>();
        StudentEntity studentEntity = (StudentEntity) session.getAttribute("student");
        StudentEntity studentEntity1 = studentService.queryStudentById(studentEntity);
        StudentInfo studentInfo = new StudentInfo();
        studentInfo.setStuId(studentEntity1.getStuId());
        studentInfo.setStuName(studentEntity1.getStuName());
        studentInfo.setSex(studentEntity1.getSex());
        studentInfo.setClassName(studentService.queryClassNameById(studentEntity1.getClassId()));
        studentInfo.setHomeName(studentService.queryHomeNameById(studentEntity1.getHomeId()));
        res.setCount(0);
        res.setData(studentInfo);
        res.setCode(0);
        res.setMsg("查询成功！！！！");
        return res;
    }


    @ApiOperation("学生选课操作")
    @GetMapping("/selectCourse")
    public AjaxResult<String> selectCourse(int couId, HttpSession session){
        AjaxResult<String> res = new AjaxResult<>();
        System.out.println(couId);
        StudentEntity student = (StudentEntity) session.getAttribute("student");
        System.out.println(student.getStuId()+"===================");
        ScoreEntity scoreEntity = new ScoreEntity();
        scoreEntity.setCouId(couId);
        scoreEntity.setStuId(student.getStuId());
        // 选课之前要先判断之前是不是选过这门课
        boolean flag = studentService.isExistselectCourse(scoreEntity);
        if (flag){
            //存在选课记录，不能再选择这门课
            res.setCode(1);
            res.setMsg("已经选过这门课了，请勿重复选择！！");

        }else{
            //没有选过这门课 ， 可以选择这门课
            studentService.selectCourse(scoreEntity);
            res.setCode(0);
            res.setMsg("选择成功！");
        }
        res.setData("");
        return res;
    }

//    @ApiOperation("学生查询自己所有的选课信息")
//    @GetMapping("/allSelectCourse")
//    public AjaxResult<List<CourseTable>> allSelectCourse(int page , int limit , HttpSession session){
//        System.out.println(page+"===="+limit);
//        StudentEntity student = (StudentEntity) session.getAttribute("student");
//        AjaxResult<List<CourseTable>> res = new AjaxResult<>();
//        //通过score表拿到选课信息
//        List<Integer> list = studentService.queryCourseListById(student.getStuId());
//        int[] ids = new int[list.size()];
//        for (int i = 0; i < list.size(); i++) {
//            ids[i] = list.get(i);
//        }
//        PageSize<int[]> pageSize = new PageSize<>();
//        pageSize.setPage(page - 1);
//        pageSize.setSize(limit);
//        pageSize.setData(ids);
//        List<CourseTable> tables = studentService.queryAllSelectCourse(pageSize);
//        res.setData(tables);
//        res.setCode(0);
//        res.setMsg("查询成功");
//        res.setCount(list.size());
//        return res;
//    }
    @ApiOperation("学生查询自己所有的选课信息")
    @GetMapping("/allSelectCourse")
    public AjaxResult<List<CourseTable>> allSelectCourse(int page , int limit , HttpSession session){
        System.out.println(page+"===="+limit);
        StudentEntity student = (StudentEntity) session.getAttribute("student");
        AjaxResult<List<CourseTable>> res = new AjaxResult<>();
        //通过score表拿到选课信息
        List<Integer> list = studentService.queryCourseListById(student.getStuId());
        int[] ids = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            ids[i] = list.get(i);
        }
        PageSize<int[]> pageSize = new PageSize<>();
        pageSize.setPage(page - 1);
        pageSize.setSize(limit);
        pageSize.setData(ids);
        List<CourseTable> tables = studentService.queryAllSelectCourse(pageSize);
        res.setData(tables);
        res.setCode(0);
        res.setMsg("查询成功");
        res.setCount(list.size());
        return res;
    }


    @ApiOperation("查询学生成绩的信息")
    @GetMapping("/queryAllGrade")
    public AjaxResult<List<ScoreTable>> queryAllGrade(int page , int limit , HttpSession session){
        AjaxResult<List<ScoreTable>> res =  new AjaxResult<>();
        StudentEntity studentEntity = (StudentEntity) session.getAttribute("student");
        PageSize<String> pageSize = new PageSize<>();
        pageSize.setPage((page - 1) * limit);
        pageSize.setSize(limit);
        pageSize.setData(studentEntity.getStuId());
        List<ScoreTable> list = studentService.queryAllGrade(pageSize);
        res.setData(list);
        res.setMsg("查询成功");
        res.setCode(0);
        res.setCount(studentService.queryAllGradeCount(studentEntity.getStuId()));
        return res;
    }


    @ApiOperation("删除该学生选择的课")
    @GetMapping("/deleteSelectCourse")
    public AjaxResult<String> deleteSelectCourse(int couId , HttpSession session){
        AjaxResult<String> res = new AjaxResult<>();
        StudentEntity studentEntity = (StudentEntity) session.getAttribute("student");
        ScoreEntity scoreEntity = new ScoreEntity();
        scoreEntity.setCouId(couId);
        scoreEntity.setStuId(studentEntity.getStuId());
        // 判断是不是这个学生选择的这门课有成绩 ， 如果有成绩则不能删除， 如果没有成绩则表示未开课，可以删除
        boolean flag = true; // 假设有成绩
        flag = studentService.isExistScore(scoreEntity);
        if(flag){
            // 不能删除
            res.setCode(1);
            res.setMsg("该门课已经结束了，不能删除");
            res.setCode(0);
            res.setData("");
        }else{
            studentService.deleteSelectCourse(scoreEntity);
            res.setCode(0);
            res.setMsg("删除成功");
            res.setCode(0);
            res.setData("");
        }
        return res;
    }


    @ApiOperation("学生修改自己的密码")
    @PostMapping("/updateStudentPassword")
    public AjaxResult<String> updateStudentPassword(@RequestBody StudentPassword studentPassword , HttpSession session){
        AjaxResult<String> res = new AjaxResult<>();
        StudentEntity studentEntity = (StudentEntity) session.getAttribute("student");
        studentEntity.setStuPassword(MD5Util.MD5Encode(studentPassword.getOldPassword() , "utf-8"));
        //查看密码是不是正确
        StudentEntity studentEntity1 = studentService.queryStudentByIdAndPwd(studentEntity);
        if (studentEntity1 != null){
            // 可以修改密码
            studentEntity.setStuPassword(MD5Util.MD5Encode(studentPassword.getNewPassword() , "utf-8"));
            studentService.updateStudentPassword(studentEntity);
            res.setData("");
            res.setMsg("修改成功");
            res.setCode(0);
            res.setCount(0);
        }else{
            // 不能修改密码
            res.setData("");
            res.setMsg("原密码错误！！！");
            res.setCode(1);
            res.setCount(0);
        }
        return res;
    }


}
